<template>
    <div class="drainage-main">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="130px">
            <el-form-item label="企微引流" :class="{ 'custom-form-item': !form.qySwitchOn }">
                <el-switch
                    @change="switchChange"
                    class="custom-switch"
                    v-model="form.qySwitchOn"
                    :active-value="true"
                    :disabled="isDisabled"
                    :inactive-value="false" />
                <span class="tip">开启后，分销员中心会展示企微员工二维码，引导分销员添加企微好友</span>
            </el-form-item>
            <template v-if="form.qySwitchOn">
                <el-form-item prop="qyName" label="引流术语">
                    <el-input
                        :disabled="isDisabled"
                        v-model="form.qyName"
                        class="custom-input"
                        maxlength="20"
                        show-word-limit
                        placeholder="请填写标题"></el-input>
                </el-form-item>
                <el-form-item prop="qyQRcode" label="企微员工二维码">
                    <!-- todo: form.img -->
                    <ImgUpload
                        :disabled="isDisabled"
                        ref="defaultImgRef"
                        v-model="form.qyQRcode"
                        accept="image/png,image/jpeg,image/jpg"
                        :is-change="true"
                        @imgStateChange="imgStateChange"
                        :currentImg="getCurrentImg(form?.qyQRcode)"
                        tip-content="图片支持jpg、png、jpeg" />
                </el-form-item>
            </template>
        </el-form>
        <div class="form-footer">
            <el-button :disabled="isDisabled" type="primary" @click="saveHandler">保存</el-button>
        </div>
    </div>
</template>

<script setup>
import { onUnmounted, onMounted, computed, reactive, ref, unref } from 'vue';
import { ElMessage } from 'element-plus';
import { isDayBefore, dateDiff, cloneDeep, format } from '@/commons/utils';
import request from '@/request/index';
import { setLayout, resetLayout } from '@/hooks/layout';
import ImgUpload from '@/components/ImageUpload.vue';
import store from '@/store/index';

const useAuth = store.useAuthStore();
const permissions = useAuth.permissions;
const isDisabled = computed(() => {
    return !permissions.has('distribution_set:wechat_edit');
});

let form = reactive({
    tab: 3,
    qySwitchOn: false,
    qyName: null,
    qyQRcode: null
});
let formClone = cloneDeep(form);
const formRef = ref();
const defaultImgRef = ref(null);

const rules = reactive({
    qyName: [
        { required: true, message: '请输入分销员名称', trigger: 'blur' },
        { min: 1, max: 20, message: '最长不超过20个字', trigger: 'blur' }
    ],
    qyQRcode: [{ required: true, trigger: 'change', message: '请设置企微员工二维码' }]
});

const switchChange = async val => {
    formClone.qySwitchOn = val;
    Object.assign(form, cloneDeep(formClone));
};

const getCurrentImg = (val, imgSrc) => {
    if (val?.[0]?.response?.data?.url) {
        return val?.[0]?.response?.data?.url;
    }
    if (!val) {
        return imgSrc || null;
    }
    if (val === 'default') {
        return imgSrc || null;
    }
    return val;
};

const setImgSrcObject = img => {
    if (img?.[0]?.response?.data?.url) {
        return img?.[0]?.response?.data?.url;
    }
    if (!img) {
        return null;
    }
    return img;
};

const imgStateChange = ({ msg }) => {
    if (['上传图片只能是jpg、png、jpeg格式！'].includes(msg)) {
        ElMessage({
            type: 'error',
            message: '上传图片只能是jpg、png、jpeg格式！'
        });
    }
    validateField('qyQRcode');
};

const saveHandler = async () => {
    if (!unref(formRef)) return;
    await unref(formRef).validate(async (valid, fields) => {
        if (valid) {
            if (defaultImgRef.value && defaultImgRef.value.loading) {
                return ElMessage({
                    type: 'error',
                    message: '图片正在上传中...，请稍后保存'
                });
            }
            // todo:setImgSrcObject
            let params = cloneDeep(form);
            params.qyQRcode = setImgSrcObject(params.qyQRcode);
            const { code } = await request('distributionSettingsSave', params);
            if (code !== 0) {
                return;
            }
            ElMessage({
                type: 'success',
                message: '保存成功'
            });
            formClone = cloneDeep(params);
        } else {
            unref(formRef).scrollToField(Object.keys(fields)?.[0]);
        }
    });
};

const clearValidate = field => {
    unref(formRef).clearValidate(field);
};

const validateField = field => {
    unref(formRef).validateField(field);
};

const getDetail = async () => {
    const { data } = await request('distributionSettingsInfo', {
        tab: 3
    });
    const { qySwitchOn, qyName, qyQRcode } = (data || {})?.info || {};
    form.qySwitchOn = qySwitchOn || false;
    form.qyName = qyName;
    form.qyQRcode = qyQRcode;
    Object.assign(formClone, cloneDeep(form));
};

onMounted(() => {
    setLayout('custom-drainage-layout');
    getDetail();
});
onUnmounted(() => {
    resetLayout('custom-drainage-layout');
});
</script>

<style lang="scss">
.custom-drainage-layout {
    min-height: calc(100vh - 260px) !important;
    max-height: calc(100vh - 260px);
    overflow-y: auto;
}
</style>
<style lang="scss" scoped>
.drainage-main {
    .custom-form-item {
        :deep {
            .el-form-item__label {
                width: 90px !important;
            }
            .el-form-item__content {
                margin-left: 0 !important;
            }
        }
    }
    :deep {
        .el-form-item__label {
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #33302d;
            /* transition: all 0.3s; */
        }
    }
    .tip {
        margin-left: 8px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #969696;
    }
    .custom-input {
        width: 380px;
    }

    .form-footer {
        position: absolute;
        bottom: 0;
        left: 1px;
        display: flex;
        align-items: center;
        justify-content: center;
        width: calc(100% - 1px);
        height: 70px;
        background-color: #fff;
        .el-button {
            width: 80px;
        }
    }
}
</style>
